import paramiko


class SSH:
    conf = None
    client = None

    def __init__(self, conf):
        self.conf = conf
        # 创建ssh客户端
        self.client = paramiko.SSHClient()
        # 第一次ssh远程时会提示输入yes或者no
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # 密码方式远程连接
        self.client.connect(conf['host'], username=conf['username'], password=conf['password'], port=conf['port'], timeout=6)
        # 互信方式远程连接
        # key_file = paramiko.RSAKey.from_private_key_file("/root/.ssh/id_rsa")
        # self.client.connect(sys_ip, 22, username=username, pkey=key_file, timeout=20)

    def __del__(self):
        self.client.close()

    def exec(self, cmd, show=True):
        # 执行命令
        try:
            std_in, std_out, std_err = self.client.exec_command(cmd)
            result = std_out.readlines()
            if show:
                for i in result:
                    print(i.replace("\n", ''))
            return result[-50:]
        except Exception as e:
            return None


class TasksSchedule:
    def __init__(self, task, ecs):
        self.task = task
        self.ecs = ecs

    def work(self):
        from conf.db import get_db
        server = SSH(self.ecs)
        result = server.exec(self.task['crontab_shell'], False)
        sql_data = {'tid': self.task['id']}
        if result is None:
            sql_data['status'] = 10  # 出错
        else:
            result = '&nbsp;'.join(result).replace('\n', '<br/>')
            sql_data['status'] = 1  # 成功
            sql_data['result'] = result
        db = get_db()
        db.insert('tasks_log', sql_data)
        return result
